import React, { Component } from 'react';
import style from './mainclasslist.module.css';
import { Table, Input, Icon, Upload } from 'antd';
import $ from 'jquery';


function img_getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
class MainClassList extends Component {
  constructor(props) {
    super(props);
  }

  state={
    id:0,
    editmod:'add',
    data:[],
    columns:[],
    showedit:false,
    edittitle:'',
    imageUrl:'',
    imgurl:'', //栏目图片
    expandedRowKeys:[],   //需要展开的行的key
    input_name:'',
    input_listname:'',
    input_detailname:'',
    input_orders:''
  }

  componentDidMount() {
    this.getallsection()
  }

  getallsection=()=>{
    const that = this;
    $.ajax({
      url:'/section',
      type:'GET',
      data:{
        act:'allsection',
      },
      dataType:'json',
      success(e){
        if(e.status == 1){
          let data = [];
          let sumkeys = [];
          let alldata = e.data;
          let i = 1;
          data = alldata.filter(e=>(e.pid == 0))
          for(let s of data){
            s.action = [
              {
                name:'添加子栏目',
                onclick:true
              },
              {
                name:'修改',
                onclick:true
              },
              {
                name:'删除',
                id:s.id,
              }
            ]
          }
          that.sum_section(data,alldata,sumkeys)
          that.act_section(data,i,0)
          console.log(data)
          that.setState({
            data,
            columns: [
              {
                title:'编号',
                dataIndex:'id',
                width:'15%',
              },
              {
                title: '栏目名称',
                dataIndex: 'name',
                width:'15%',
              },
              {
                title:'列表文件名',
                dataIndex:'listname',
                width:'20%',
              },
              {
                title:'详情页文件名',
                dataIndex:'detailname',
                width:'15%',
              },
              {
                title: '排序',
                dataIndex: 'orders',
                width:'15%',
              },
              {
                title: '操作',
                dataIndex: 'action',
                render:(obj,res)=>{return(<ul className={style.action_ul}>
                  {
                    obj.map((e,index)=>{return( 
                      e.onclick==1?<li key={index} onClick={that.openedit.bind(that,e.name,e.id)}>{e.name}</li>:e.onclick==2?<li key={index} onClick={that.openxiugai.bind(that,res.name,res.id,res.listname,res.detailname,res.orders,res.pic)}>{e.name}</li>:<li className={style.del} onClick={that.del.bind(that,e.id)} key={index}>{e.name}</li>
                    )})
                  }
                </ul>)},
                width:'20%',
              },
            ],
            expandedRowKeys:sumkeys,
            allkey:sumkeys,
          })
        }
      }
    })
  }

  sum_section=(data,alldata,sumkeys)=>{ //整合栏目函数
    for(let obj of data){
      if(alldata.filter(e=>(e.pid == obj.id)).length != 0){
        obj.children = alldata.filter(e=>(e.pid == obj.id))
        sumkeys.push(obj.id)
        this.sum_section(obj.children,alldata,sumkeys)
      }
    }
  }

  act_section=(data,i,last_pid)=>{
    let if_add = true
    if(i>=4){
      if_add = false
    }
    // console.log(i)
    for(let obj of data){
      if(obj.pid == 0){
        i = 1
      }
      if(if_add){
        obj.action = [
          {
            name:'添加子栏目',
            onclick:1,
            id:obj.id
          },
          {
            name:'修改',
            onclick:2
          },
          {
            name:'删除',
            id:obj.id,
          }
        ]
      }else{
        obj.action = [
          {
            name:'修改',
            onclick:2
          },
          {
            name:'删除',
            id:obj.id,
          }
        ]
      }
      if(obj.children){
        i++
        this.act_section(obj.children,i)
      }
    }
  }

  Expand=(expanded, record)=>{
    let key
    if(expanded){
      key = this.state.expandedRowKeys;
      for(let i of this.state.allkey){
        if(i == record.id){
          key.push(i)
        }
      }
    }else{
      key = [];
      for(let i of this.state.expandedRowKeys){
        if(i != record.id){
          key.push(i)
        }
      }
    }
    this.setState({
      expandedRowKeys:key
    })
  }

  changeInput_name=(e)=>{
    this.setState({
      input_name:e.target.value      
    })
  }

  changeInput_listname=(e)=>{
    this.setState({
      input_listname:e.target.value      
    })
  }

  changeInput_detailname=(e)=>{
    this.setState({
      input_detailname:e.target.value      
    })
  }

  changeInput_orders=(e)=>{
    this.setState({
      input_orders:e.target.value      
    })  
  }

  openxiugai=(name,id,listname,detailname,orders,pic)=>{
    console.log(name,id,listname,detailname,orders,pic)
    this.setState({
      showedit:true,
      id:id,
      editmod:'updata',
      input_name:name,
      input_listname:listname,
      input_detailname:detailname,
      input_orders:orders,
      imageUrl:pic
    })
  }

  del=(id)=>{
    const that = this;
    console.log(id)
    $.ajax({
      url:'/section',
      dataType:'json',
      data:{
        act:'del',
        id:id       
      },
      success(e){
        if(e.status == 1){
          that.getallsection()          
        }
        alert(e.msg)       
      }
    })
  }

  check=()=>{
    if(this.state.input_name==""){
      alert('填写栏目名')
      return false;
    }else if(this.state.input_listname==""){
      alert('填写列表文件名')
      return false;
    }else if(this.state.input_detailname==""){
      alert('填写详情页文件名')
      return false;
    }else if(this.state.input_orders==""){
      alert('填写排序')
      return false;
    }else{
      return true;
    }
  }

  submit=()=>{  //提交
    // console.log(this.state.id)
    const that = this;
    if(this.check()){
      $.ajax({
        url:'/section',
        dataType:'json',
        data:{
          act:this.state.editmod=="add"?'submit':'goupdate',
          id:this.state.id,
          name:this.state.input_name,
          listname:this.state.input_listname,
          detailname:this.state.input_detailname,
          orders:this.state.input_orders,
          pic:this.state.imgurl
        },
        success(e){
          console.log(e)
          alert(e.msg)
          if(e.status == 1){
            that.getallsection()
            that.closeedit()            
          }
        }
      })
    }
  }

  openedit=(name,id)=>{
    this.setState({
      showedit:true,
      editmod:'add',
      edittitle:name,
      id
    })
  }

  closeedit=()=>{
    this.setState({
      showedit:false,
      input_name:'',
      input_listname:'',
      input_detailname:'',
      input_orders:''
    })
  }

  imghandleChange = info => {
    // console.log(info)
    var imgurl = info.file.response!=undefined?info.file.response.imgurl:'';
    // Get this url from response in real world.
    img_getBase64(info.file.originFileObj, imageUrl =>
      this.setState({
        imageUrl,
        imgurl
      }),
    );
  };

  render() { 
    const { imageUrl } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    return (
      <div className={style.main}>
        <div className={style.classlist}>
          <Table pagination={false} onExpand={this.Expand} expandedRowKeys={this.state.expandedRowKeys} rowKey='id' columns={this.state.columns} dataSource={this.state.data} />
        </div>
        <div style={this.state.showedit?{display:'flex'}:{display:'none'}} className={style.edit}>
          <div className={style.edit_div}>
            <div className={style.edit_header}>{this.state.editmod=="add"?'添加子栏目':'修改子栏目'}<Icon onClick={this.closeedit} type="close"/></div>
            <div className={style.edit_content}>
              <div className={style.edit_content_div}><span>栏目名：</span><Input placeholder='请输入栏目名' onChange={this.changeInput_name.bind(this)} value={this.state.input_name}/></div>
              <div className={style.edit_content_div}><span>列表页文件名：</span><Input placeholder='请输入列表页文件名' onChange={this.changeInput_listname.bind(this)} value={this.state.input_listname}/></div>
              <div className={style.edit_content_div}><span>详情页文件名：</span><Input placeholder='请输入详情页文件名' onChange={this.changeInput_detailname.bind(this)} value={this.state.input_detailname}/></div>
              <div className={style.edit_content_div}><span>排序号：</span><Input placeholder='请输入排序号' onChange={this.changeInput_orders.bind(this)} value={this.state.input_orders}/></div>
              <div className={`${style.edit_content_div} ${style.edit_content_upload}`}><span>栏目图片：</span>
                <Upload
                  listType="picture-card"
                  className={style.edit_content_upload}
                  showUploadList={false}
                  action="/upload"
                  onChange={this.imghandleChange}
                >
                  {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                </Upload>
              </div>
              <div className={style.gosubmit} onClick={this.submit}>提交</div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
 
export default MainClassList;


// 树状结构注意：<Table onExpand={this.Expand} expandedRowKeys={this.state.data.map(item=>item.id)} rowKey='id' columns={this.state.columns} dataSource={this.state.data} />
//代码中rowKey='id'（默认rowKey='key'），把id当作key。
//expandedRowKeys={this.state.data.map(item=>item.id)} 默认展开所有行